package com.xuequ.answerme.details;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.xuequ.answerme.R;
import com.xuequ.answerme.adapter.DetailRecyclerViewAdapter;
import com.xuequ.answerme.beans.AnswerBean;
import com.xuequ.answerme.beans.QuestionBean;
import com.xuequ.answerme.beans.UserBean;
import com.xuequ.answerme.manager.AnswerManager;
import com.xuequ.answerme.manager.QuestionManager;
import com.xuequ.answerme.manager.UserManager;
import com.xuequ.answerme.question.AnswerQuestionActivity;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobUser;
import me.drakeet.materialdialog.MaterialDialog;

/**
 * Created by Shijie on 2015/9/30.
 */
public class QuestionDetailActivity extends AppCompatActivity {

    private CardView cardView;
    private TextView remindText;

    private QuestionBean questionBean;// 详情界面的问题bean

    private MaterialDialog materialDialog;

    private UserBean userBean;

    private AnswerManager answerManager;// 详情界面的答案Manager
    private UserManager userManager;// 详情界面的用户Manager
    private QuestionManager questionManager;// 详情界面的问题Manager

    private Toolbar toolBar;
    private DetailRecyclerViewAdapter mAdapter;// 问题答案adapter
    private List<AnswerBean> mData;// 此问题的所有答案构成的list
    private RecyclerView mRecyclerView;

    private SwipeRefreshLayout swipeRefreshLayout;

    private FloatingActionButton fabQuestionDetail;// 刷新按钮
    private FloatingActionButton fabFocus;// 关注按钮
    private FloatingActionButton fabAnswer;// 回答按钮
    private FloatingActionButton fabMain;// 菜单按钮

    private boolean isButtonsAppear = false;// 关注和刷新按钮是否显示了
    private boolean isFocus = false;// 此问题是否被次用户关注了
    private boolean isLoadingMore = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_detail2);

        initViews();//初始化控件和数据
        checkTheQuestion();//检测问题是否有效

    }

    /**
     * 检测问题是否还在
     */
    private void checkTheQuestion() {
        questionManager.checkTheQuestion(QuestionDetailActivity.this, questionBean.getObjectId(), new QuestionManager.CheckTheQuestionListener() {
            @Override
            public void checkTheQuestionOnSuccess(QuestionBean question) {
                //如果还在就刷新问题的答案
                questionBean = question;
                cardView.setVisibility(View.VISIBLE);
                refreshNewAnswers();//第一次刷新此问题的所有答案
            }

            @Override
            public void checkTheQuestionOnFailure(String failureMsg) {
                //问题无效则提醒用户
                showQuestionDismiss();
            }
        });
    }

    /**
     * 提示用户问题无效
     */
    private void showQuestionDismiss() {

        materialDialog = new MaterialDialog(this);
        materialDialog.setTitle(":(");
        materialDialog.setMessage("此问题可能已经被删除或者网络原因无法查看，请点击OK返回上一层");
        materialDialog.setPositiveButton("OK", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDialog.dismiss();
                finish();//返回主界面
            }
        });
        materialDialog.show();
    }

    /**
     * 初始化控件、变量
     */
    private void initViews() {

        //new something
        if (questionManager == null) {
            questionManager = new QuestionManager();
        }

        if (userManager == null) {
            userManager = new UserManager();
        }
        if (answerManager == null) {
            answerManager = new AnswerManager();
        }

        //获取从上个Activity传来的QuestionBean，作为此详情界面的核心问题
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        questionBean = (QuestionBean) bundle.getSerializable("questionBean");
        Log.i("QuestionDetail","questionBean question`````````````"+questionBean.getQuestion_title());

        userBean = BmobUser.getCurrentUser(this, UserBean.class);

        //设置toolbar
        toolBar = (Toolbar) findViewById(R.id.question_detail_tool_bar);
        setSupportActionBar(toolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.question_detail_swipeRefreshLayout);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshNewAnswers();
            }
        });

        cardView = (CardView) findViewById(R.id.question_detail_refresh_remind_card);
        remindText = (TextView) findViewById(R.id.question_detail_refresh_remind_text);

        //初始化Refresh按钮并添加点击事件
        fabQuestionDetail = (FloatingActionButton) findViewById(R.id.question_detail_detail_fab);
        fabQuestionDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                questionDetail();
            }
        });

        //初始化Focus按钮并添加点击事件
        fabFocus = (FloatingActionButton) findViewById(R.id.question_detail_focus_fab);
        fabFocus.setClickable(false);
        fabFocus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //在整个关注过程开始时使按钮不可点击，防止冲突
                fabFocus.setClickable(false);
                toggleButtons();
                userManager.focusOrNot(QuestionDetailActivity.this, questionBean, userBean, isFocus, new UserManager.FocusOrNotListener() {
                    @Override
                    public void focusOrNotOnSuccess() {
                        Log.i("QuestionDetailActivity", "-------------------------> focus success ");
                        questionManager.focusNumberChange(QuestionDetailActivity.this, questionBean.getObjectId(), isFocus, new QuestionManager.FocusOrNotListener() {
                            @Override
                            public void focusOrNotOnSuccess() {
                                Log.i("QuestionDetailActivity", "-------------------------> change number of focus success ");
                                isFocus = !isFocus;
                                fabFocus.setClickable(true);
                                if (isFocus) {
                                    fabFocus.setImageResource(R.drawable.am_isfocus);
                                } else {
                                    fabFocus.setImageResource(R.drawable.am_focus);
                                }
                            }

                            @Override
                            public void focusOrNotOnFailure(String failureMsg) {
                                fabFocus.setClickable(true);
                                Log.i("QuestionDetailActivity", "-------------------------> change number of focus failure ");
                            }
                        });
                    }

                    @Override
                    public void focusOrNotOnFailure(String failureMsg) {
                        Log.i("QuestionDetailActivity", "-------------------------> focus failure " + failureMsg);
                        fabFocus.setClickable(true);
                    }
                });

            }
        });
        checkIsFocus();

        fabAnswer = (FloatingActionButton) findViewById(R.id.question_detail_answer_fab);
        fabAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleButtons();
                //跳转到回答页面
                Intent intent = new Intent(QuestionDetailActivity.this, AnswerQuestionActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("questionBean", questionBean);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });


        fabMain = (FloatingActionButton) findViewById(R.id.question_detail_main_fab);
        fabMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleButtons();
            }
        });

        mRecyclerView = (RecyclerView) findViewById(R.id.detail_recycler_view);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);

        mData = new ArrayList<>();
        mAdapter = new DetailRecyclerViewAdapter(mData);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnRefreshDoneListener(new DetailRecyclerViewAdapter.OnRefreshDoneListener() {
            @Override
            public void onRefreshDone() {
                swipeRefreshLayout.setRefreshing(false);
                mRecyclerView.scrollToPosition(0);
            }

            @Override
            public void onLoadMore() {
                loadMoreAnswers();
            }

            @Override
            public void onLoadMoreDone() {
                isLoadingMore = false;
            }
        });

        mAdapter.setOnItemClickListener(new DetailRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                Intent intent = new Intent(QuestionDetailActivity.this, AnswerDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("answerBean", mData.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    private void loadMoreAnswers() {

        if (!isLoadingMore) {
            isLoadingMore = true;
            answerManager.loadMoreAnswers(this, mData.get(mData.size() - 1).getCreatedAt(), questionBean, new AnswerManager.LoadMoreAnswersListener() {
                @Override
                public void loadMoreAnswersOnSuccess(List<AnswerBean> answerBeans) {
                    Log.i("QuestionDetailActivity", "load more data size is ------------------------->" + answerBeans.size());
                    if (answerBeans.size() != 1) {
                        mAdapter.addOldData(answerBeans);
                    } else {
                        isLoadingMore = false;
                    }
                }

                @Override
                public void loadMoreAnswersOnFailure(String failureMsg) {
                    isLoadingMore = false;
                }
            });
        }
    }

    private void questionDetail() {
        if (materialDialog == null) {
            materialDialog = new MaterialDialog(this);
        }
        materialDialog.setTitle(questionBean.getQuestion_title());
        materialDialog.setMessage(questionBean.getQuestion_description());
        materialDialog.setPositiveButton("OK", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDialog.dismiss();
            }
        });
        materialDialog.show();
    }

    /**
     * 刷新答案
     */
    private void refreshNewAnswers() {

        answerManager.findAllAnswers(QuestionDetailActivity.this, questionBean, new AnswerManager.FindAllAnswersListener() {
            @Override
            public void findAllAnswersOnSuccess(List<AnswerBean> answers) {
                Log.i("QuestionDetailActivity", "refresh new data size is ------------------------->" + answers.size());
                if (answers.size() == 0) {
                    swipeRefreshLayout.setRefreshing(false);
                    remindText.setText("没有人回答:(");
                } else {
                    Log.i("QuestionDetailActivity", "-------------------------> answer size " + answers.size());
                    cardView.setVisibility(View.GONE);
                    mAdapter.refreshData(answers);
                }
            }

            @Override
            public void findAllAnswersOnFailure(String failureMSG) {
                cardView.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);
                //提示没有人回答
                Snackbar.make(swipeRefreshLayout, failureMSG, Snackbar.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 查看此问题是否已经被关注
     */
    private void checkIsFocus() {
        userManager.checkIsFocus(QuestionDetailActivity.this, userBean, new UserManager.FindFocusListener() {
            @Override
            public void findFocusOnSuccess(List<QuestionBean> questionBeans, int count) {
                if (questionBeans.size() == 0) {
                    Log.i("focus", "-------------------------------->isn't focus");
                    //不改变
                } else {
                    Log.i("focus", "-------------------------------->is focus");
                    //改变样式
                    fabFocus.setImageResource(R.drawable.am_isfocus);
                    isFocus = true;
                }
                fabFocus.setClickable(true);
            }

            @Override
            public void findFocusOnFailure(String failureMsg) {
                fabFocus.setFocusable(true);
            }
        });
    }

    /**
     * 显示 和 隐藏 关注、刷新按钮
     */
    private void toggleButtons() {
        if (isButtonsAppear) {
            Log.i("toggleButtons", "buttons are ready to disappear");
            // close
            // button alpha 1->0
            // button translationX 0 -> -100
            final PropertyValuesHolder propertyValuesHolderX = PropertyValuesHolder.ofFloat("translationY", 0);
            final PropertyValuesHolder propertyValuesHolderAlpha = PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f);
            ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(fabFocus, propertyValuesHolderX, propertyValuesHolderAlpha).setDuration(100);
            animator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    fabFocus.setClickable(false);

                }

                @Override
                public void onAnimationEnd(Animator animation) {

                    ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(fabQuestionDetail, propertyValuesHolderX, propertyValuesHolderAlpha).setDuration(100);
                    animator.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                            fabQuestionDetail.setClickable(false);

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(fabAnswer, propertyValuesHolderX, propertyValuesHolderAlpha).setDuration(100);
                            animator.addListener(new Animator.AnimatorListener() {
                                @Override
                                public void onAnimationStart(Animator animation) {
                                    fabAnswer.setClickable(false);
                                }

                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    isButtonsAppear = false;
                                }

                                @Override
                                public void onAnimationCancel(Animator animation) {

                                }

                                @Override
                                public void onAnimationRepeat(Animator animation) {

                                }
                            });
                            animator.start();


                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    animator.start();

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            animator.start();

        } else {
            //open
            Log.i("toggleButtons", "buttons are ready to appear");
            final PropertyValuesHolder propertyValuesHolder = PropertyValuesHolder.ofFloat("translationY", -300f);
            final PropertyValuesHolder propertyValuesHolderAlpha = PropertyValuesHolder.ofFloat("alpha", 0f, 1f);
            ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(fabFocus, propertyValuesHolder, propertyValuesHolderAlpha).setDuration(100);
            animator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    fabFocus.setClickable(true);

                    PropertyValuesHolder propertyValuesHolder = PropertyValuesHolder.ofFloat("translationY", -165f);
                    ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(fabQuestionDetail, propertyValuesHolder, propertyValuesHolderAlpha).setDuration(100);
                    animator.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            fabQuestionDetail.setClickable(true);
                            PropertyValuesHolder propertyValuesHolder = PropertyValuesHolder.ofFloat("translationY", -435f);
                            ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(fabAnswer, propertyValuesHolder, propertyValuesHolderAlpha).setDuration(100);
                            animator.addListener(new Animator.AnimatorListener() {
                                @Override
                                public void onAnimationStart(Animator animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    fabAnswer.setClickable(true);
                                    isButtonsAppear = true;
                                }

                                @Override
                                public void onAnimationCancel(Animator animation) {

                                }

                                @Override
                                public void onAnimationRepeat(Animator animation) {

                                }
                            });
                            animator.start();

                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    animator.start();

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            animator.start();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_right, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if(item.getItemId() == android.R.id.home)
        {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
